package JavaAIODemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AioClient {
    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        // 1. 创建 AsynchronousSocketChannel
        AsynchronousSocketChannel clientChannel = AsynchronousSocketChannel.open();

        // 2. 连接服务器（异步）
        Future<Void> future = clientChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
        future.get(); // 等待连接完成
        System.out.println("Connected to server");

        // 3. 发送数据到服务器
        String message = "Hello, AIO Server!";
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
        clientChannel.write(buffer).get(); // 异步写，并等待完成
        System.out.println("Sent to server: " + message);

        // 4. 接收服务器的响应
        buffer.clear();
        clientChannel.read(buffer).get(); // 异步读，并等待完成
        buffer.flip();
        String response = new String(buffer.array(), 0, buffer.limit());
        System.out.println("Received from server: " + response);

        clientChannel.close(); // 关闭连接
    }
}
